package com.demo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.FormBody.Builder;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class OkHttpUtil {

  private static final ObjectMapper MAPPER = new ObjectMapper();

  private static final MediaType JSON_TYPE = MediaType.parse("application/json");


  public static String doGet(Call.Factory client, String url) {
    return doGet(client, url, null);
  }

  public static String doGet(Call.Factory client, String url, Map<String, String> header) {
    Request request = new Request.Builder().headers(headers(header)).url(url).get().build();
    return execute(client, request);
  }

  public static String doPost(Call.Factory client, String url, Object data) {
    return doPost(client, url, null, data);
  }

  public static String doPost(Call.Factory client, String url, Map<String, String> header, Object data) {
    RequestBody body = RequestBody.create(JSON_TYPE, encodeData(data));
    Request request = new Request.Builder().headers(headers(header)).url(url).post(body).build();
    return execute(client, request);
  }

  public static String doPostWithForm(Call.Factory client, String url, Map<String, String> param) {
    FormBody.Builder builder = new Builder();
    param.forEach(builder::add);
    FormBody body = builder.build();
    Request request = new Request.Builder().url(url).post(body).build();
    return execute(client, request);
  }

  private static String execute(Call.Factory client, Request request) {
    try (Response response = client.newCall(request).execute()) {
      if (!response.isSuccessful()) {
        String responseStr = response.body().string();
        log.error("httpCode = {}，response = {}", response.code(), responseStr);
        return null;
      }
      return response.body().string();
    } catch (IOException e) {
      log.error("http请求异常，exception = {}", ExceptionUtils.getStackTrace(e));
      throw new RuntimeException(e);
    }
  }

  public static String encodeData(Object data) {
    if (data == null) {
      return "";
    }
    boolean json = isJson(data.toString());
    if (json) {
      return (String) data;
    }
    try {
      return MAPPER.writeValueAsString(data);
    } catch (JsonProcessingException e) {
      log.error("序列化json数据异常，exception = {}", ExceptionUtils.getStackTrace(e));
      throw new RuntimeException(e);
    }
  }

  public static boolean isJson(String input) {
    ObjectMapper mapper = new ObjectMapper();
    try {
      // 尝试将字符串解析为JsonNode树状结构（对象或数组）
      mapper.readTree(input);
      return true;
    } catch (Exception e) {
      return false;
    }
  }

  private static Headers headers(Map<String, String> header) {
    Headers.Builder builder = new Headers.Builder();
    if (header == null || header.isEmpty()) {
      return builder.build();
    }
    for (String key : header.keySet()) {
      builder.add(key, header.get(key));
    }
    return builder.build();
  }

}